package com.sinosoft.sinopay.apiservise.chinapay.util;

import chinapay.Base64;
import chinapay.PrivateKey;
import chinapay.SecureLink;
import org.apache.log4j.Logger;

/**
 * 【上银联签名、验签工具类】
 * @Description: TODO
 * @author liuyjsh@sinosoft.com.cn
 * @date 2016年6月21日 下午7:30:07 
 * @version V1.0
 */
public abstract class ChinapaySignUtil {

    private static Logger logger = Logger.getLogger(ChinapaySignUtil.class);
    
    private String path;
    
    
    public static void main(String[] args) {
//        String sign = checkKeyd("absdfklsdkf","808080211388326");
//        System.out.println(sign);
        test();
    }
    public static void test(){
        String signMsg = "123";
        
        String plainDataBase64 = new String(Base64.encode(signMsg.getBytes()));
        PrivateKey privateKey = new PrivateKey();
        String merid = "808080211388326";
        
        String keyPath = "MerPrK_uat.key";
        boolean b = privateKey.buildKey(merid, 0, keyPath);
        if(!b){
            System.out.println("签名有误");
            return;
        }
        
        SecureLink secureLink = new SecureLink(privateKey);
        String sign =  secureLink.Sign(plainDataBase64);
        System.out.println(sign);
        
    }
    /** 
     * 对数据进行签名
     * @Title: Sign 
     * @Description: 对数据进行签名
     * @param signMsg - 需要签名数据
     * @return
     */
    public static String sign(String signMsg) {
        String plainDataBase64 = new String(Base64.encode(signMsg.getBytes()));
        PrivateKey privateKey = new PrivateKey();
        String merid = ChinapayConfig.getMerId();
        String keyPath = getKeyPath(ChinapayConfig.getMerPrkKey());
        boolean b = privateKey.buildKey(merid, 0, keyPath);
        if (b == false) {
            return null;
        }
        SecureLink secureLink = new SecureLink(privateKey);
        return secureLink.Sign(plainDataBase64);
    }

    /**
     * 
     * 上银联验证签名方法
     * @Title: checkSign 
     * @Description: 上银联验证签名方法
     * @param plainData
     * @param sign
     * @return
     */
    public static boolean checkSign(String plainData, String sign) {
        PrivateKey key = new PrivateKey();
        String merid = ChinapayConfig.getMerId();
        String keyPath = getKeyPath(ChinapayConfig.getPgPubkKey());
        key.buildKey(merid, 0, keyPath);
        SecureLink secureLink = new SecureLink(key);
        return secureLink.verifyAuthToken(plainData, sign);
    }

    /*
     * 通过相对路径获取绝对路径
     * @Title: getKeyPath 
     * @Description: 通过相对路径获取绝对路径
     * @param relativePath
     * @return 绝对路径
     */
    private static String getKeyPath(String keyName) {
        String path = ChinapaySignUtil.class.getClassLoader().getResource("/").toString();
        path = path.replaceAll("file:/", "");
        path += "config/chinapay/" + keyName;
        return path;
    }
    
}
